package com.ruoyi.buss.task.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.pagehelper.PageInfo;
import com.ruoyi.buss.task.domain.*;
import com.ruoyi.buss.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.buss.customer.domain.DataCustomerInfo;
import com.ruoyi.buss.customer.mapper.DataCustomerInfoMapper;
import com.ruoyi.buss.domain.customer.rsp.ResCustinfo;
import com.ruoyi.buss.grade.domain.DataCustGradeInfoNew;
import com.ruoyi.buss.grade.domain.DataCustomQuery;
import com.ruoyi.buss.grade.mapper.DataCustomQueryMapper;
import com.ruoyi.buss.grade.service.IDataCustGradeInfoNewService;
import com.ruoyi.buss.grid.cj.domain.DataCustomerInfoVO;
import com.ruoyi.buss.grid.cj.mapper.DataWgWgcjMapper;
import com.ruoyi.buss.grid.sh.mapper.DataGtgshMapper;
import com.ruoyi.buss.grid.sq.mapper.DataWgWgsqMapper;
import com.ruoyi.buss.grid.zysc.mapper.DataWgZyscKhMapper;
import com.ruoyi.buss.system.domain.DataDictionary;
import com.ruoyi.buss.system.domain.UserRole;
import com.ruoyi.buss.system.mapper.DataDictionaryMapper;
import com.ruoyi.buss.system.service.IIusOrgInfoService;
import com.ruoyi.buss.task.mapper.DataPlanTaskRelationMapper;
import com.ruoyi.buss.task.mapper.DataTaskExRecordBackMapper;
import com.ruoyi.buss.task.mapper.DataTaskExRecordImageMapper;
import com.ruoyi.buss.task.mapper.DataTaskExRecordMapper;
import com.ruoyi.buss.task.mapper.DataTaskInfoMapper;
import com.ruoyi.buss.task.mapper.DataUserTaskRelationMapper;
import com.ruoyi.buss.task.service.IDataTaskExRecordService;
import com.ruoyi.buss.task.service.IDataTaskInfoService;
import com.ruoyi.buss.task.service.IDataUserTaskRelationService;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.api.model.LoginUser;

/**
 * 营销任务Service业务层处理
 * 
 * @author sxy
 * @date 2021-07-16
 */
@Service
public class DataTaskInfoServiceImpl implements IDataTaskInfoService {
	@Autowired
	private DataTaskInfoMapper dataTaskInfoMapper;
	@Autowired
	private DataTaskExRecordMapper dataTaskExRecordMapper;
	@Autowired
	private DataCustomerInfoMapper dataCustomerInfoMapper;
	@Autowired
	private IDataUserTaskRelationService iDataUserTaskRelationService;
	@Autowired
	private DataPlanTaskRelationMapper dataPlanTaskRelationMapper;
	@Autowired
	private DataTaskExRecordImageMapper dataTaskExRecordImageMapper;
	@Autowired
	private DataGtgshMapper dataGtgshMapper;
	@Autowired
	private DataTaskExRecordBackMapper dataTaskExRecordBackMapper;
	@Autowired
	private DataWgWgcjMapper dataWgWgcjMapper;

	@Autowired
	private DataWgWgsqMapper dataWgWgsqMapper;

	@Autowired
	private DataWgZyscKhMapper dataWgZyscKhMapper;

	@Autowired
	private DataUserTaskRelationMapper dataUserTaskRelationMapper;
	@Autowired
	private IDataCustGradeInfoNewService iDataCustGradeInfoNewService;
	@Autowired
	private DataDictionaryMapper dataDictionaryMapper;
	@Autowired
	private DataCustomQueryMapper dataCustomQueryMapper;
	@Autowired
	private IDataTaskExRecordService iDataTaskExRecordService;
	@Autowired
	private IIusOrgInfoService iIusOrgInfoService;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;
	@Override
	@Transactional
	public DataTaskInfo item(String taskId, LoginUser userInfo) {

		DataTaskInfo taskInfoVO = dataTaskInfoMapper.selectDataTaskInfoById(taskId);
		if (null == taskInfoVO) {
			return taskInfoVO;
		}
		if ("0".equals(taskInfoVO.getTaskType()) || "0".equals(taskInfoVO.getIfGroup())) {
			DataPlanTaskRelation planTaskVO = dataPlanTaskRelationMapper.item(taskId);

			if (null != planTaskVO && !StringUtils.isEmpty(planTaskVO.getPlanCode())) {
				DataCustomQuery dataCustomQuery = dataCustomQueryMapper
						.selectDataCustomQueryById(planTaskVO.getPlanCode());
				String planName = dataCustomQuery.getPlanName();
				taskInfoVO.setGroupName(planName);
				taskInfoVO.setGroupCode(planTaskVO.getPlanCode());
			}
		}

		if ("1".equals(taskInfoVO.getTaskType()) || "1".equals(taskInfoVO.getIfGroup())) {
			List<String> customerIdList = dataUserTaskRelationMapper.listByTask(taskId);
			taskInfoVO.setCustomList(customerIdList);
		}

		if (!StringUtils.isEmpty(taskInfoVO.getUserId()) && !"-1".equals(taskInfoVO.getUserId())) {
			taskInfoVO.setUserName("");
		}

		// 获取营销目标名称(产品代码转中文)
		String targetName = "";
		List<String> targetList = Arrays.asList(taskInfoVO.getTaskTarget().split(","));
		StringBuffer targerBuff = new StringBuffer();
		for (String temp : targetList) {
			DataDictionary dictionaryDO = dataDictionaryMapper.itemByCode(temp);
			if (null != dictionaryDO) {
				targerBuff.append(dictionaryDO.getDicName());
				targerBuff.append(",");
			}
		}
		String targetNames = targerBuff.toString();
		if (StringUtils.isNotEmpty(targetNames)) {
			targetName = targetNames.substring(0, targetNames.length() - 1);
		}
		taskInfoVO.setTargetName(targetName);

		return taskInfoVO;
	}

	/**
	 * 查询营销任务列表(taskType=0查总行，taskType=1查个人)
	 * 
	 * @param dataTaskInfo
	 * @return
	 */
	@Override
	public List<DataTaskInfo> taskList(DataTaskInfo dataTaskInfo, LoginUser userInfo) {
		String orgId = userInfo.getSysUser().getDept().getOrgId();
		String userId = userInfo.getSysUser().getUserName();
		String orgName = userInfo.getSysUser().getDept().getDeptName();
		List<DataTaskInfo> doList = new ArrayList<DataTaskInfo>();
		dataTaskInfo.setOrgId(null);
		dataTaskInfo.setUserId(null);
		if (userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office")) {

		} else if (userInfo.getRoles().contains("zhhz")) {
			dataTaskInfo.setOrgId(orgId);
			if("1".equals(dataTaskInfo.getZhType())) {
				dataTaskInfo.setUserId(userId);
			}
		} else if (userInfo.getRoles().contains("common")) {

			if (StringUtils.isEmpty(dataTaskInfo.getIfGroup())) {
				String OrgUserId = dataDictionaryMapper.queryOrgUserId(orgId);
				if (StringUtils.isEmpty(OrgUserId)) {
					return doList;
				}
				dataTaskInfo.setOrgId(orgId);
				dataTaskInfo.setUserId(userId);
				dataTaskInfo.setCreateUserOr(OrgUserId);
			} else if ("1".equals(dataTaskInfo.getIfGroup())) {
				dataTaskInfo.setOrgId(orgId);
				dataTaskInfo.setUserId(userId);
			} else {
				dataTaskInfo.setOrgId(orgId);
				dataTaskInfo.setUserId(null);
			}
		} else {
			throw new CustomException("没有权限进行该操作!");
		}
		// 如果参数中的birthday不为空 则表示查询的是快要到生日的客户
		if ("1".equals(dataTaskInfo.getSyType())) {
			// 取四天后的日期
			String now = new SimpleDateFormat("MMdd").format(DateUtilss.getdate(4));
			// 若是查询快要生日的客户,需要设置一下客户的生日日期
			dataTaskInfo.setBirthday(now);
		}
		if ("1".equals(dataTaskInfo.getRwType())) { //rwtype 1和3 不知道有啥区别，我看都一样
			doList = dataTaskInfoMapper.taskInfolist(dataTaskInfo);
		} else if ("2".equals(dataTaskInfo.getRwType())) {//rwtype 2 表示查询支行行长创建的任务
			doList = dataTaskInfoMapper.taskInfolist(dataTaskInfo);
		} else if ("3".equals(dataTaskInfo.getRwType())) {
			doList = dataTaskInfoMapper.taskInfolist(dataTaskInfo);
		} else {
			// 个人营销任务列表查询
			if (userInfo.getRoles().contains("zhhz")) {
				dataTaskInfo.setUserId(null);
			}
			doList = dataTaskInfoMapper.list(dataTaskInfo);
		}

		for (DataTaskInfo temp : doList) {
			if ("0".equals(temp.getIfGroup())) {
				DataPlanTaskRelation planTaskVO = dataPlanTaskRelationMapper.item(temp.getTaskId());
				if (null != planTaskVO) {
					String planName = dataCustomQueryMapper.getName(planTaskVO.getPlanCode());
					temp.setGroupCode(planTaskVO.getPlanCode());
					temp.setGroupName(planName);
				}
				temp.setUserName(orgName);
			}
		//	voList.add(temp);
		}

		return doList;
	}

	/**
	 * 添加营销任务
	 *
	 * @param taskAddInfo TaskInfoAddVO 营销任务信息
	 * @param userId      String 当前登录用户ID
	 * @param orgId       String 机构ID
	 * @param taskIdRef   Ref<String> 任务ID
	 * @return ErrorCode
	 */
	@Override
	@Transactional
	public Map<String,String> insertTask(DataTaskInfo taskAddInfo, LoginUser userInfo) {
		String orgId = userInfo.getSysUser().getDept().getOrgId();
		String userId = userInfo.getSysUser().getUserName();

		if (StringUtils.isEmpty(taskAddInfo.getType())) {
			taskAddInfo.setType("1");
		}

		if ("0".equals(taskAddInfo.getTaskType())) {
			// 总行任务只有总行可以添加
			if (!(userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office") || userInfo.getRoles().contains("zhhz"))) {
				throw new CustomException("不是总行人员，无法添加总行营销任务");

			}
		}

		if (StringUtils.isEmpty(userId)) {
			throw new CustomException("用户没有登录");
		}
		DataTaskInfo taskInfo = new DataTaskInfo();

		BeanUtils.copyProperties(taskAddInfo, taskInfo);

		if (taskInfo.getOrgId() == null) {
			taskInfo.setUserId(userId);
			taskInfo.setOrgId(orgId);
		}
		taskInfo.setCreateUser(userId);
		taskInfo.setUpdateUser(userId);
		taskInfo.setFinishNum(0);// 新添加的任务，完成数量为0
		// 获取ID
		Map<String,String> map = new HashMap<>();
		String taskId = GetOnlyId.getOnlyId();
		taskInfo.setTaskId(taskId);
		map.put("taskId",taskId);
		// 如果是总行创建的任务，则没有指向客户经理
		if ("0".equals(taskAddInfo.getTaskType())) {
			taskInfo.setUserId("-1");
		}
		// 如果没有指定分配客户经理，则视为客户经理添加个人营销任务
		if (StringUtils.isEmpty(taskInfo.getUserId())) {
			taskInfo.setUserId(userId);
		}

		// 设置任务开始时间和结束时间，其中开始时间是当天第一秒，结束时间是当天最后一秒
		taskInfo.setBeginDate(DateUtilss.beginOfDate(DateUtilss.strToDate(taskAddInfo.getBeginDateStr())));
		taskInfo.setEndDate(DateUtilss.endOfDate(DateUtilss.strToDate(taskAddInfo.getEndDateStr())));
		taskInfo.setCreateTime(DateUtils.getNowDate());
		taskInfo.setStatus("1");



		List<String> idcardList = new ArrayList<String>();
		if (!StringUtils.isEmpty(taskAddInfo.getTaskSyType())) {
			DataPlanTaskRelation vo = new DataPlanTaskRelation();
			vo.setSyType(taskAddInfo.getTaskSyType());
			// 客户生日
			if ("1".equals(vo.getSyType())) {
				// 取四天后的日期
				String now = new SimpleDateFormat("MMdd").format(DateUtilss.getdate(4));
				// 若是查询快要生日的客户,需要设置一下客户的生日日期
				vo.setBirthday(now);
				idcardList = dataTaskInfoMapper.listByOrgUser1(vo);
			}
			// 查询大额资金变动
			if ("2".equals(vo.getSyType())) {
				idcardList = dataTaskInfoMapper.listByOrgUser2(vo);
			}
			// 存款产品到期
			if ("3".equals(vo.getSyType())) {
				idcardList = dataTaskInfoMapper.listByOrgUser3(vo);
			}
			// 理财产品到期
			if ("4".equals(vo.getSyType())) {
				idcardList = dataTaskInfoMapper.listByOrgUser4(vo);
			}
			// 贷款产品到期
			if ("5".equals(vo.getSyType())) {
				idcardList = dataTaskInfoMapper.listByOrgUser5(vo);
			}
			if (idcardList.size() > 0) {
				taskAddInfo.setCustomList(idcardList);
			}
			taskInfo.setSyType(vo.getSyType());
		}
		int told = dataTaskInfoMapper.insertDataTaskInfo(taskInfo);
		if (told >= 1) {
			insertInfo(userId, taskInfo, taskAddInfo.getCustomList(), userInfo);
		}
		return map;
	}

	/**
	 * 修改营销反馈
	 * 
	 * @param dataTaskInfo
	 * @param userInfo
	 * @return
	 */
	@Override
	@Transactional
	public AjaxResult updateExInfo(DataTaskInfo dataTaskInfo, LoginUser userInfo) {

		String orgId = userInfo.getSysUser().getDept().getOrgId();
		String userId = userInfo.getSysUser().getUserName();

		DataTaskExRecord dataTaskExRecord = new DataTaskExRecord();
		dataTaskExRecord.setId(dataTaskInfo.getExId());
		dataTaskExRecord.setRecordDesc(dataTaskInfo.getRecordDesc());
		if (userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office")) {

		} else if (userInfo.getRoles().contains("zhhz")) {
			dataTaskExRecord.setBankId(orgId);
		} else if (userInfo.getRoles().contains("common")) {
			dataTaskExRecord.setBankId(orgId);
			dataTaskExRecord.setUserId(userId);
		} else {
			return AjaxResult.error("没有权限进行该操作!");
		}

		dataTaskExRecordMapper.updateDataTaskExRecord(dataTaskExRecord);
		return AjaxResult.success();
	}

	/**
	 * 检验是否可以开始营销
	 */
	@Override
	public AjaxResult ExRecord(DataTaskInfo dataTaskInfo, LoginUser userInfo) {

		if (StringUtils.isEmpty(dataTaskInfo.getTaskId()) || dataTaskInfo.getTaskId().equals("null")) {
			return AjaxResult.error("营销反馈ID为空或该客户没有开始营销!");
		}
		Integer type = dataTaskInfoMapper.getExTaskType(dataTaskInfo.getTaskId());
		if (type > 0) {
			return AjaxResult.success();
		} else {
			return AjaxResult.error();
		}
	}

	/**
	 * 添加任务
	 *
	 * @param userId     String 当前登录人ID
	 * @param taskInfo   TaskInfoVO 营销任务主体信息
	 * @param idCardList List<String> 营销任务指定客户集合信息
	 * @return ErrorCode
	 */
	@Transactional
	private AjaxResult insertInfo(String userId, DataTaskInfo taskInfo, List<String> idCardList, LoginUser userInfo) {
		String orgId = userInfo.getSysUser().getDept().getOrgId();
		DataPlanTaskRelation planTaskVO = new DataPlanTaskRelation();

		planTaskVO.setUserId(userId);
		planTaskVO.setOrgId(orgId);
		planTaskVO.setStatus("1");
		if (userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office")) {

			/******** 总行 **********/
			// 管理员角色或者总行人员，查询所有客户，只添加根据方案方式添加营销任务
			// 如果是总行创建的任务，则没有指向客户经理
			planTaskVO.setPlanCode(taskInfo.getGroupCode());
			planTaskVO.setTaskId(taskInfo.getTaskId());

			dataPlanTaskRelationMapper.insertDataPlanTaskRelation(planTaskVO);
			this.inserTaskCustomRelation(taskInfo, idCardList);
		} else if (userInfo.getRoles().contains("zhhz")) {

			/******** 支行行长 **********/
			if (taskInfo.getIfGroup().equals("1")) {
				taskInfo.setUserId(null);
				taskInfo.setOrgId(orgId);

				// 1、根据指定客户添加营销任务
				this.inserTaskCustomRelation(taskInfo, idCardList);
			} else if (taskInfo.getIfGroup().equals("0")) {
				// 2、根据方案添加营销任务
				if (!StringUtils.isEmpty(taskInfo.getUserId()) && !"-1".equals(taskInfo.getUserId())) {
					// 如果是指定客户经理的营销任务
					planTaskVO.setUserId(taskInfo.getUserId());
				}
				// 如果没指定客户经理
				planTaskVO.setPlanCode(taskInfo.getGroupCode());
				planTaskVO.setTaskId(taskInfo.getTaskId());
				planTaskVO.setOrgId(orgId);
				dataPlanTaskRelationMapper.insertDataPlanTaskRelation(planTaskVO);
			}
		} else if (userInfo.getRoles().contains("common")) {

			/******* 客户经理 **********/
			// 支行客户经理或者柜员，查询所属自己的客户

			if (taskInfo.getIfGroup().equals("1")) {
				taskInfo.setUserId(userId);
				taskInfo.setOrgId(orgId);
				// 1、指定客户
				this.inserTaskCustomRelation(taskInfo, idCardList);
			} else if (taskInfo.getIfGroup().equals("0")) {
				// 2、根据方案添加
				planTaskVO.setUserId(userId);
				planTaskVO.setPlanCode(taskInfo.getGroupCode());
				planTaskVO.setTaskId(taskInfo.getTaskId());
				planTaskVO.setOrgId(orgId);
				dataPlanTaskRelationMapper.insertDataPlanTaskRelation(planTaskVO);
			}
		} else {
			// 其他的暂时不返回数据
			return AjaxResult.error("没有权限执行此操作");
		}
		return AjaxResult.success();
	}

	/**
	 * 如果营销任务指定客户，需要添加营销任务和客户的关联关系
	 *
	 * @param taskinfo   TaskInfoVO 营销任务
	 * @param idCardList List 客户身份证号集合
	 * @return ErrorCode
	 */
	@Transactional
	private AjaxResult inserTaskCustomRelation(DataTaskInfo taskinfo, List<String> idCardList) {
		// 如果客户集合为空，则返回成功
		if (ListUtil.isNullOrEmpty(idCardList)) {
			return AjaxResult.success();
		}

		for (String idCard : idCardList) {
			List<ResCustinfo> resCustinfos = new ArrayList<ResCustinfo>();
			Map<String, String> map = new HashMap<String, String>();
			switch (Integer.parseInt(taskinfo.getType())) {
			case 1:
				resCustinfos = dataCustomerInfoMapper.getCustInfo(idCard);
				if (!ListUtil.isNullOrEmpty(resCustinfos)) {
					map.put("orgId", resCustinfos.get(0).getOrg_id());
					map.put("userId", resCustinfos.get(0).getUser_id());
					map.put("name", resCustinfos.get(0).getName());
				} else {
					map.put("orgId", null);
					map.put("userId", null);
					map.put("name", null);
				}
				break;
			case 2:
				map = dataGtgshMapper.getShInfo(idCard);
				if (map.get("orgId") == null || "".equals(map.get("orgId"))) {
					List<Map<String, Object>> list = this.dataTaskInfoMapper.findOrganizationFromUntechOrgMap();// flag
																												// 0:有地址对照
																												// 1：城区支行
					if (list != null && list.size() > 0) {
						String address = dataGtgshMapper.getAddress(idCard);

						for (Map<String, Object> orgAndAddress : list) {
							String addr = orgAndAddress.get("ADDRESS").toString();
							if (addr.contains("支行") && address != null) {
								addr = addr.substring(0, addr.indexOf("支行"));
								// 用身份证地址与UNTECH_ORG_MAP表中比对，如果身份证地址中包含对照表中的地址，则匹配成功，否则按城区支行平均分配
								if (address.contains(addr)) {
									map.put("orgId", orgAndAddress.get("ORGNO").toString());
									break;
								}
							}

						}
					}
				}
				break;
			case 3:
				map = dataWgWgcjMapper.getCJInfo(idCard);
				break;
			case 4:
				map = dataWgWgsqMapper.getSQInfo(idCard);
				break;
			case 5:
				map = dataWgZyscKhMapper.getZYSCInfo(idCard);
				break;
			default:
				resCustinfos = dataCustomerInfoMapper.getCustInfo(idCard);
				if (!ListUtil.isNullOrEmpty(resCustinfos)) {
					map.put("orgId", resCustinfos.get(0).getOrg_id());
					map.put("userId", resCustinfos.get(0).getUser_id());
					map.put("name", resCustinfos.get(0).getName());
				} else {
					map.put("orgId", null);
					map.put("userId", null);
					map.put("name", null);
				}
				break;
			}

			// 总行任务从存量表中取管户
			if ("0".equals(taskinfo.getTaskType())) {
				taskinfo.setUserId(map.get("userId"));
				taskinfo.setOrgId(map.get("orgId"));
			} else {
				// 支行任务从存量表表中取本支行的管户
				if (taskinfo.getUserId() == null) {
					if (!taskinfo.getOrgId().equals(map.get("orgId"))) {
						// 若存量表中不存在本支行的管户 则 设置管户人为null
						taskinfo.setUserId(null);
					} else {
						taskinfo.setUserId(map.get("userId"));
					}
				}
			}

			DataUserTaskRelation userTaskRelationVO = new DataUserTaskRelation();
			userTaskRelationVO.setId(GetOnlyId.getOnlyId());
			userTaskRelationVO.setIdCard(idCard);
			userTaskRelationVO.setTaskId(taskinfo.getTaskId());
			userTaskRelationVO.setOrgId(taskinfo.getOrgId());
			userTaskRelationVO.setUserId(taskinfo.getUserId());
			userTaskRelationVO.setCusName(map.get("name") == null ? "" : map.get("name"));
			userTaskRelationVO.setType(taskinfo.getType());
			userTaskRelationVO.setCreateTime(DateUtils.getNowDate());
			userTaskRelationVO.setStatus("1");
			userTaskRelationVO.setComplete("0");
			// 5表示当前指定客户为专业市场客户
			if ("5".equals(taskinfo.getType())) {
				userTaskRelationVO.setMarketId(taskinfo.getMarketId());
			}
			dataUserTaskRelationMapper.insertDataUserTaskRelation(userTaskRelationVO);
		}
		return AjaxResult.success();
	}

	@Transactional
	public void relationTaskCustomer() {

		DataPlanTaskRelation dataPlanTaskRelation = new DataPlanTaskRelation();
		dataPlanTaskRelation.setStatus("1");
		List<DataPlanTaskRelation> planTaskVOList = dataPlanTaskRelationMapper
				.selectDataPlanTaskRelationList(dataPlanTaskRelation);

		for (DataPlanTaskRelation temp : planTaskVOList) {

			DataCustGradeInfoNew dataCustGradeInfoNew = new DataCustGradeInfoNew();
			dataCustGradeInfoNew.setPlanCode(temp.getPlanCode());
//			dataCustGradeInfoNew.setOrgId(temp.getOrgId());
//			dataCustGradeInfoNew.setUserId(temp.getUserId());

			List<DataCustGradeInfoNew> gradeInfoList = iDataCustGradeInfoNewService
					.queryResultNews(dataCustGradeInfoNew);
//			List<DataUserTaskRelation> dataUserTaskRelationList = new ArrayList<DataUserTaskRelation>();
			for (DataCustGradeInfoNew gradeInfo : gradeInfoList) {

				DataUserTaskRelation dataUserTaskRelation = new DataUserTaskRelation();
				dataUserTaskRelation.setId(GetOnlyId.getOnlyId());
				dataUserTaskRelation.setIdCard(gradeInfo.getIdCard());

				dataUserTaskRelation.setUserId(gradeInfo.getUserId());
				dataUserTaskRelation.setCusName(gradeInfo.getName());
				dataUserTaskRelation.setTaskId(temp.getTaskId());
				dataUserTaskRelation.setType(gradeInfo.getType());
				dataUserTaskRelation.setMarketId(gradeInfo.getMarketId());

				if ((gradeInfo.getOrgId() == null || "".equals(gradeInfo.getOrgId()))
						&& "2".equals(gradeInfo.getType())) {
					List<Map<String, Object>> list = dataDictionaryMapper.findOrganizationFromUntechOrgMap();// flag
																												// 0:有地址对照
																												// 1：城区支行
					if (list != null && list.size() > 0) {
						String address = dataGtgshMapper.getAddress(gradeInfo.getIdCard());
						if(address != null) {
							for (Map<String, Object> orgAndAddress : list) {
								String addr = orgAndAddress.get("ADDRESS").toString();
								if (addr.contains("支行")) {
									addr = addr.substring(0, addr.indexOf("支行"));
									// 用身份证地址与UNTECH_ORG_MAP表中比对，如果身份证地址中包含对照表中的地址，则匹配成功，否则按城区支行平均分配
									if (address.contains(addr)) {
										String orgId = orgAndAddress.get("ORGNO").toString();
										gradeInfo.setOrgId(orgId);
										break;
									}
								}
							}
						}
						
					}
				}
				dataUserTaskRelation.setOrgId(gradeInfo.getOrgId());
				
				
				dataUserTaskRelationMapper.insertDataUserTaskRelation(dataUserTaskRelation);
//				dataUserTaskRelationList.add(dataUserTaskRelation);
//				
//				
//				if (dataUserTaskRelationList.size() == 1000) {
//					dataUserTaskRelationMapper.insertDataUserTaskRelationList(dataUserTaskRelationList);
//					dataUserTaskRelationList = new ArrayList<DataUserTaskRelation>();
//				}
			}
//			if (dataUserTaskRelationList.size() > 0) {
//				dataUserTaskRelationMapper.insertDataUserTaskRelationList(dataUserTaskRelationList);
//			}
			temp.setStatus("0");
			dataPlanTaskRelationMapper.updateDataPlanTaskRelation(temp);
		}
	}

	/**
	 * 查询营销任务对应的客户列表
	 */
	@Override
	public List<DataCustomerInfoVO> listCustom(DataTaskInfo dataTaskInfo, LoginUser userInfo) {

		DataTaskInfo taskInfoVO = this.item(dataTaskInfo.getTaskId(), userInfo);

		if (null == taskInfoVO) {

		}

		DataPlanTaskRelation planTaskIdCardVO = new DataPlanTaskRelation();
		planTaskIdCardVO.setTaskId(taskInfoVO.getTaskId());
		planTaskIdCardVO.setCusName(dataTaskInfo.getName());
		planTaskIdCardVO.setIdCard(dataTaskInfo.getIdCard());

		// 如果参数中的birthday不为空 则表示查询的是快要到生日的客户
		if ("1".equals(dataTaskInfo.getSyType())) {
			// 取四天后的日期
			String now = new SimpleDateFormat("MMdd").format(DateUtilss.getdate(4));
			// 若是查询快要生日的客户,需要设置一下客户的生日日期
			planTaskIdCardVO.setBirthday(now);
		}

		planTaskIdCardVO.setSyType(dataTaskInfo.getSyType());
		List<DataCustomerInfoVO> doList = new ArrayList<DataCustomerInfoVO>();
		// 1、获取指定用户信息
		if ("1".equals(taskInfoVO.getIfGroup())) {
			// 只通过任务ID查询
			doList = iDataUserTaskRelationService.listIdCardByTask(planTaskIdCardVO);
		} else if ("0".equals(taskInfoVO.getIfGroup())) {
			// 2、获取方案关联的客户
			try {
				UserRole userRole = GetRoleUtil.GetRole(userInfo);
				planTaskIdCardVO.setOrgId(userRole.getOrgId());
				planTaskIdCardVO.setUserId(userRole.getUserId());
			} catch (Exception e) {
				throw new CustomException(e.getMessage());
			}
			doList = iDataUserTaskRelationService.listCustomerByOrgUser(planTaskIdCardVO);
		}

		return doList;
	}

	/**
	 * 查询客户列表信息
	 *
	 * @param condition
	 * @return
	 */
	public List<DataTaskInfo> taskListCustom(DataTaskInfo dataTaskInfo, LoginUser userInfo) {

		List<DataTaskInfo> list = new ArrayList<DataTaskInfo>();
		try {
			UserRole userRole = GetRoleUtil.GetRole(userInfo);
			if(dataTaskInfo.getOrgId()==null&&dataTaskInfo.getUserId()==null){
				dataTaskInfo.setOrgId(userRole.getOrgId());
				dataTaskInfo.setOrgId(userRole.getUserId());
			}

		} catch (Exception e) {
			throw new CustomException(e.getMessage());
		}
		list = dataUserTaskRelationMapper.taskListCustom(dataTaskInfo);
		DataTaskInfo taskInfoVO = this.item(dataTaskInfo.getTaskId(), userInfo);

		if (null == taskInfoVO) {
			throw new CustomException("参数错误");
		}

		return list;
	}

	@Transactional
	public AjaxResult insertTaskExRecord(DataTaskExRecord dataTaskExRecord, LoginUser userInfo) {
		if (StringUtils.isEmpty(dataTaskExRecord.getId())) {
			return AjaxResult.error("参数错误,id为空(取营销反馈表ID<exId>)");
		}
		try {
			UserRole userRole = GetRoleUtil.GetRole(userInfo);
			dataTaskExRecord.setUserId(userRole.getUserId());
			dataTaskExRecord.setBankId(userRole.getOrgId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/**
		 * 营销成功之后,修改营销状态,将退回状态修改为正常
		 */
		dataTaskExRecord.setStatus("1");// 营销状态 0待营销 1营销完成
		dataTaskExRecord.setIsBack("0");// 退回状态 0正常 1退回
		dataTaskExRecord.setUpdateTime(DateUtils.getNowDate());
		Map<String, Integer> map = new HashMap<>();
		map = iDataTaskExRecordService.countEX(dataTaskExRecord, map);

		if (map.get("num") != null && map.get("num") > 0) {
			return AjaxResult.error("当前客户已经营销完成,无需再次营销");
		}
		// 更新营销反馈信息
		dataTaskExRecordMapper.updateDataTaskExRecord(dataTaskExRecord);

		// 将原来得老图片修改为无效
		DataTaskExRecordImage dataTaskExRecordImage = new DataTaskExRecordImage();
		dataTaskExRecordImage.setTaskExRecordId(dataTaskExRecord.getId());
		dataTaskExRecordImage.setDelFlag("0");
		dataTaskExRecordImage.setCreateTime(DateUtils.getNowDate());
		dataTaskExRecordImage.setUpdateTime(DateUtils.getNowDate());
		dataTaskExRecordImageMapper.updateDataTaskExRecordImage(dataTaskExRecordImage);

		dataTaskExRecordImage.setDelFlag("1");
		dataTaskExRecordImage.setIdCard(dataTaskExRecord.getIdCard());
		dataTaskExRecordImage.setTaskId(dataTaskExRecord.getTaskId());

		// 插入新的营销图片
		if (dataTaskExRecord.getExPics().length > 0) {
			for (String str : dataTaskExRecord.getExPics()) {
				dataTaskExRecordImage.setExPic(str);
				dataTaskExRecordImageMapper.insertDataTaskExRecordImage(dataTaskExRecordImage);
			}
		}

/*		int count = map.get("num");
		// 如果已经存在过营销反馈信息，则无需更改营销任务的完成数量
		if (0 < count) {
			return AjaxResult.success();
		}*/

		// 判断当前营销的客户是否为营销任务的最后一个客户，如果是最后一个客户，则更新DATA_TASK_INFO 营销任务为与完成
		int completedCount = dataUserTaskRelationMapper.selectCompleted(dataTaskExRecord.getTaskId(),
				dataTaskExRecord.getIdCard());
		// 等于0 表示除了当前客户，没有未营销的客户
		if (completedCount == 0) {
			DataTaskInfo task = new DataTaskInfo();
			task.setTaskId(dataTaskExRecord.getTaskId());
			task.setUpdateTime(DateUtils.getNowDate());
			task.setComplete("1");
			dataTaskInfoMapper.updateDataTaskInfo(task);
		}

		// 修改营销任务该客户状态为已营销
		dataUserTaskRelationMapper.completed(dataTaskExRecord.getTaskId(), dataTaskExRecord.getIdCard());

		// 查看是否存在 退回，如果是退回的，则更新退回表中的状态为已修复
		DataTaskExRecordBack dataTaskExRecordBack = new DataTaskExRecordBack();
		dataTaskExRecordBack.setStatus("0");
		dataTaskExRecordBack.setTaskExRecordId(dataTaskExRecord.getId());
		List<DataTaskExRecordBack> taskExRecordBackVO = dataTaskExRecordBackMapper
				.selectDataTaskExRecordBackList(dataTaskExRecordBack);
		if (taskExRecordBackVO.size() > 0) {
			dataTaskExRecordBack.setStatus("1");
			dataTaskExRecordBack.setTaskExRecordId(dataTaskExRecord.getId());
			dataTaskExRecordBack.setUpdateTime(DateUtils.getNowDate());
			dataTaskExRecordBackMapper.updateDataTaskExRecordBack(dataTaskExRecordBack);
		}

		int addCode = dataTaskInfoMapper.addTaskFinishNum(dataTaskExRecord.getTaskId());
		if (addCode <= 0) {
			throw new CustomException("增加营销任务完成数异常");
		}
		return AjaxResult.success();
	}

	@Transactional
	public AjaxResult startTaskExRecord(DataTaskExRecord taskExRecordVO, LoginUser userInfo) {

		String lockKey = "startTask" + taskExRecordVO.getIdCard();
		RedisLockL lock = null;

		try {

			lock = new RedisLockL(redisTemplate, lockKey, 10000, 20000);

			DataTaskExRecord dataTaskExRecord = new DataTaskExRecord();
			dataTaskExRecord.setTaskId(taskExRecordVO.getTaskId());
			dataTaskExRecord.setIdCard(taskExRecordVO.getIdCard());

			DataTaskExRecord one = dataTaskExRecordMapper.selectDataTaskExRecordById(dataTaskExRecord);

			if (lock.lock()) {

				String orgId = userInfo.getSysUser().getDept().getOrgId();
				String userId = userInfo.getSysUser().getUserName();
				if (StringUtils.isEmpty(taskExRecordVO.getTaskId())) {
					return AjaxResult.error("营销任务ID为空");
				}

				// 未开始的营销任务不可以添加营销记录
				boolean result = this.checkTaskIfBegin(taskExRecordVO.getTaskId());

				if (!result) {
					return AjaxResult.error("营销任务还未开始");
				}
				// 已结束的营销任务不可以添加营销记录
				result = this.checkTaskIfEnd(taskExRecordVO.getTaskId());

				if (result) {
					return AjaxResult.error("营销任务已结束");
				}

				int count = dataTaskExRecordMapper.countEX(taskExRecordVO);
				if (count > 0){
//					return AjaxResult.error("当前任务中所在客户已经营销完成,无法再次营销!");
					return AjaxResult.success(one);
				}

				if (one != null) {
					return AjaxResult.success(one);
				} else {
					taskExRecordVO.setId(GetOnlyId.getOnlyId());
					taskExRecordVO.setUserId(userId);
					taskExRecordVO.setBankId(orgId);
					taskExRecordVO.setStatus("0");
					taskExRecordVO.setCreateTime(DateUtils.getNowDate());
					taskExRecordVO.setUpdateTime(DateUtils.getNowDate());
					dataTaskExRecordMapper.insertDataTaskExRecord(taskExRecordVO);
					dataTaskExRecord.setId(taskExRecordVO.getId());
					taskExRecordVO = dataTaskExRecordMapper.selectDataTaskExRecordById(dataTaskExRecord);
				}
				return AjaxResult.success(taskExRecordVO);
			} else {
				return AjaxResult.success(one);
			}

		} catch (Exception e) {
			return AjaxResult.error(e.getMessage());
//            logger.error("appKey[{}]反欺诈回调mq监听处理失败", appKey);
		} finally {
			if (lock != null) {
				lock.unlock();
			}
		}

	}

	/**
	 * 查询客户营销记录集合
	 * 
	 * @param taskId
	 * @param idCard
	 * @param userInfo
	 * @return
	 */
	public List<DataTaskExRecord> listTaskExRecord(String taskId, String idCard, LoginUser userInfo) {
		return iDataTaskExRecordService.listByTask(taskId, idCard, userInfo);
	}

	/**
	 * 支行行长查看营销进度
	 * 
	 * @param conditionVO
	 * @param userId
	 * @param userInfo
	 * @return
	 */
	public List<TaskReportsVO> queryReports(DataTaskInfo conditionVO, LoginUser userInfo) {
		List<TaskReportsVO> result = new ArrayList<>();
		try {
			UserRole userRole = GetRoleUtil.GetRole(userInfo);
			conditionVO.setOrgId(userRole.getOrgId());
			conditionVO.setUserId(userRole.getUserId());
			result = this.getReportsByUser(conditionVO);
		} catch (Exception e) {
			throw new CustomException(e.getMessage());
		}
		return result;
	}

	public AjaxResult delete(DataTaskInfo condition, LoginUser userInfo) {
		String userId = userInfo.getSysUser().getUserName();
		if (StringUtils.isEmpty(condition.getTaskId())) {
			return AjaxResult.error("营销任务ID为空");
		}
		DataTaskInfo taskInfoVO = this.item(condition.getTaskId(), userInfo);
		if (null == taskInfoVO) {
			return AjaxResult.success();
		}

		// 判断营销任务是否已经开始
//		boolean result = this.checkTaskIfBegin(condition.getTaskId());
//		boolean endResult = this.checkTaskIfEnd(condition.getTaskId());
//		if (result) {
//			if (endResult) {
//				return AjaxResult.error("营销任务已结束");
//			}
//			return AjaxResult.error("营销任务已开始");
//		}

		// 删除营销任务判断，如果是总行营销任务，必须是总行人员可以删除；如果是个人营销任务，必须是创建者才可以删除该任务
		if (!Constant.GEREN_TASK.equals(taskInfoVO.getTaskType())) {
			return AjaxResult.error("不是个人营销任务，无法删除");
		} 
		if (!userId.equals(taskInfoVO.getCreateUser())) {
			return AjaxResult.error("不是任务创建者，无法删除该任务");
		}
		// 根据taskId对表DATA_TASK_INFO、DATA_PLAN_TASK_RELATION、DATA_USER_TASK_RELATION进行删除操作
//		dataPlanTaskRelationMapper.deleteDataPlanTaskRelationById(condition.getTaskId());
		DataTaskInfo dataTaskInfo = new  DataTaskInfo();
		dataTaskInfo.setStatus("0");
		dataTaskInfo.setUpdateTime(DateUtils.getNowDate());
		dataTaskInfo.setTaskId(taskInfoVO.getTaskId());
		dataTaskInfoMapper.updateDataTaskInfo(dataTaskInfo);
		
//		dataUserTaskRelationMapper.deleteDataUserTaskRelationByTaskId(condition.getTaskId());
		return AjaxResult.success();
	}

	public AjaxResult refreshTask(String taskID, LoginUser userInfo) {

		String orgId = userInfo.getSysUser().getDept().getOrgId();
		String userId = userInfo.getSysUser().getUserName();
		if (StringUtils.isEmpty(taskID)) {
			return AjaxResult.error("营销任务ID为空");
		}

		if (!(userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office")
				|| userInfo.getRoles().contains("zhhz"))) {
			return AjaxResult.error("没有权限执行此操作");
		}
		DataUserTaskRelation dataUserTaskRelation = new DataUserTaskRelation();
		dataUserTaskRelation.setOrgId(orgId);
		dataUserTaskRelation.setComplete("0");
		dataUserTaskRelation.setTaskId(taskID);
		List<DataUserTaskRelation> userTaskRelationDOList = dataUserTaskRelationMapper
				.selectDataUserTaskRelationList(dataUserTaskRelation);
		if (ListUtil.isNullOrEmpty(userTaskRelationDOList)) {
			return AjaxResult.error("未查询到相应的营销任务");
		}

		for (DataUserTaskRelation userTaskRelationDO : userTaskRelationDOList) {
			int total = dataTaskExRecordMapper.queryExInfo(userTaskRelationDO.getTaskId(),
					userTaskRelationDO.getIdCard());
			if (total != 0) {
				System.out.println("任务正在进行中................" + userTaskRelationDO.getIdCard());
				continue;
			}
			List<String> userIdList = dataCustomerInfoMapper.queryInfo(userTaskRelationDO.getIdCard());
			if (!ListUtil.isNullOrEmpty(userIdList)) {
				String userid = userIdList.get(0);
				if (StringUtils.isEmpty(userid) || userid.startsWith("XN")) {
					continue;
				} else {
					DataCustomerInfo dataCustomerInfo = new DataCustomerInfo();
					dataCustomerInfo.setIdCard(userTaskRelationDO.getIdCard());
					dataCustomerInfo.setUserId(userId);
					dataCustomerInfoMapper.updateDataCustomerInfoByIdCard(dataCustomerInfo);
				}
			}
		}
		return AjaxResult.success();
	}

	public AjaxResult taskReturn(DataTaskInfo taskCustomerVO, LoginUser userInfo) {
		DataUserTaskRelation dataUserTaskRelation = new DataUserTaskRelation();
		if (userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office")) {

		} else if (userInfo.getRoles().contains("zhhz")) {
			// 支行行长，查询所有本支行客户
			String orgId = userInfo.getSysUser().getDept().getOrgId();
			dataUserTaskRelation.setOrgId(orgId);
		} else {
			throw new CustomException("当前登录角色无权限操作");
		}

		dataUserTaskRelation.setTaskId(taskCustomerVO.getTaskId());
		dataUserTaskRelation.setIdCard(taskCustomerVO.getIdCard());
		dataUserTaskRelation.setStatus("1");

		List<DataUserTaskRelation> dataUserTaskRelationList = dataUserTaskRelationMapper
				.selectDataUserTaskRelationList(dataUserTaskRelation);
		DataUserTaskRelation vo = null;
		if (dataUserTaskRelationList.size() > 0) {
			vo = dataUserTaskRelationList.get(0);
			// 修改营销任务表状态
			DataTaskInfo task = new DataTaskInfo();
			task.setTaskId(taskCustomerVO.getTaskId());
			task.setComplete("0");// 任务状态修改为 待营销
			dataTaskInfoMapper.updateDataTaskInfo(task);

			// 修改营销任务和客户关系表 为退回 complete 为0
			dataUserTaskRelationMapper.updateCompleted(taskCustomerVO.getTaskId(), taskCustomerVO.getIdCard());

			// DATA_TASK_EX_RECORD 标记下当前哪条记录退回，用于再app或pc端操作 退回
			DataTaskExRecord taskExRecord = new DataTaskExRecord();
			taskExRecord.setId(taskCustomerVO.getTaskExRecordId());
			taskExRecord.setIsBack("1");// 退回状态
			taskExRecord.setStatus("0");// 待营销
			dataTaskExRecordMapper.updateDataTaskExRecord(taskExRecord);

			// 插入退回记录
			dataTaskExRecordMapper.insertBack(taskCustomerVO.getTaskExRecordId(), taskCustomerVO.getMsg());
		} else {
			throw new CustomException("当前登录角色无权限操作");
		}

		return AjaxResult.success();
	}

	public List<DataTaskInfo> marketTaskList(DataTaskInfo dataTaskInfo, LoginUser userInfo) {

		List<DataTaskInfo> doList = new ArrayList<DataTaskInfo>();

		String orgId = userInfo.getSysUser().getDept().getOrgId();
		String userId = userInfo.getSysUser().getUserName();

//		dataTaskInfo.setOrgId(null);
//		dataTaskInfo.setUserId(null);
		// 如果是admin用户不做处理
		if (userInfo.getRoles().contains("zhhz")) {
			dataTaskInfo.setOrgId(orgId);
			if("1".equals(dataTaskInfo.getZhType())) {
				dataTaskInfo.setUserId(userId);
			}
		} else if (userInfo.getRoles().contains("common")) {
			dataTaskInfo.setOrgId(orgId);
			dataTaskInfo.setUserId(userId);
		}else if (userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office")) {
			dataTaskInfo.setOrgId(null);
			dataTaskInfo.setUserId(null);
		}

		doList = dataTaskInfoMapper.marketTaskList(dataTaskInfo);

		/*for (DataTaskInfo vo : doList) {
			String taskTarget = vo.getTaskTarget();
			// CK,DK,ETC,XYK,SJYH,WY,DXQY,SDDJ,SYB,POS
			taskTarget = taskTarget.replace("CK", "存款");
			taskTarget = taskTarget.replace("DK", "贷款");
			taskTarget = taskTarget.replace("ETC", "ETC");
			taskTarget = taskTarget.replace("XYK", "信用卡");
			taskTarget = taskTarget.replace("SJYH", "手机银行");
			taskTarget = taskTarget.replace("WY", "网银");
			taskTarget = taskTarget.replace("DXQY", "短信签约");
			taskTarget = taskTarget.replace("SDDJ", "水电代缴");
			taskTarget = taskTarget.replace("SYB", "收银宝");
			taskTarget = taskTarget.replace("POS", "POS");
			vo.setTaskTarget(taskTarget);
			// 0代表对私 1代表对公
			String dgds = "0";
			String str = dataTaskInfoMapper.getdgds(vo.getIdCard());
			if (str != null) {
				// 存量客户对公对私为空默认为对私
				dgds = str;
			} else if (dataTaskInfoMapper.getdgdsGtgsh(vo.getIdCard()) != null) {
				// 个体工商户全都为对公
				dgds = "1";
			}
		*//*	if (dataTaskInfoMapper.getdgdsZysc(vo.getIdCard()) != null && "5".equals(vo.getType())) {
				// 专业市场对公对私为空的默认对公
				dgds = dataTaskInfoMapper.getdgdsZysc(vo.getIdCard());
			}*//*
			if (vo.getType() != null && "2".equals(vo.getType())) {
				// 个体工商户全都为对公
				dgds = "1";
			}
			vo.setDgds(dgds);
		}*/

		return doList;
	}
	public List<ExprotDataTaskInfo> exprotMarketTaskList(ExprotDataTaskInfo dataTaskInfo, LoginUser userInfo) {

		List<ExprotDataTaskInfo> doList = new ArrayList<ExprotDataTaskInfo>();

		String orgId = userInfo.getSysUser().getDept().getOrgId();
		String userId = userInfo.getSysUser().getUserName();

		// 如果是admin用户不做处理
		if (userInfo.getRoles().contains("zhhz")) {
			dataTaskInfo.setOrgId(orgId);
		} else if (userInfo.getRoles().contains("common")) {
			dataTaskInfo.setOrgId(orgId);
			dataTaskInfo.setUserId(userId);
		}

		doList = dataTaskInfoMapper.exprotMarketTaskList(dataTaskInfo);


		return doList;
	}
	public List<DataTaskInfo> getMarketStatus(DataTaskInfo dataTaskInfo, LoginUser userInfo) {
		List<DataTaskInfo> taskInfoVO = new ArrayList<DataTaskInfo>();

		Map<String, Object> map = new HashMap<String, Object>();

		String orgId = userInfo.getSysUser().getDept().getOrgId();
		String userId = userInfo.getSysUser().getUserName();
		if (userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office")) {

		} else if (userInfo.getRoles().contains("zhhz")) {
			map.put("orgId", orgId);
			if("1".equals(dataTaskInfo.getZhType())) {
				map.put("userId", userId);
			}
		} else if (userInfo.getRoles().contains("common")) {
			map.put("orgId", orgId);
			map.put("userId", userId);
		} else {
			throw new CustomException("没有权限进行该操作");
		}

		// 0是任务数 1是到个人
		if ("0".equals(dataTaskInfo.getType())) {
			taskInfoVO = dataTaskInfoMapper.getMarketStatusAll(map);
		} else if ("1".equals(dataTaskInfo.getType())) {
			map.put("taskId", dataTaskInfo.getTaskId());
			taskInfoVO = dataTaskInfoMapper.getMarketStatus(map);
		}
		return taskInfoVO;
	}

	public AjaxResult updateExImage(DataTaskExRecordImage dataTaskExRecordImage, LoginUser userInfo) {
		if (StringUtils.isEmpty(dataTaskExRecordImage.getExId())) {
			return AjaxResult.error("营销反馈ID为空 >>exId");
		}
		if (StringUtils.isEmpty(dataTaskExRecordImage.getIdCard())) {
			return AjaxResult.error("证件号码不能为空 >>idCard");
		}
		if (StringUtils.isEmpty(dataTaskExRecordImage.getTaskId())) {
			return AjaxResult.error("taskId不能为空");
		}
		if (StringUtils.isEmpty(dataTaskExRecordImage.getExPic())) {
			return AjaxResult.error("图片路径不能为空 >>exPic");
		}
		try {
			// 没有权限则会报错
			GetRoleUtil.GetRole(userInfo);
		} catch (Exception e) {
			throw new CustomException(e.getMessage());
		}
		dataTaskExRecordImage.setTaskExRecordId(dataTaskExRecordImage.getExId());
		dataTaskExRecordImage.setDelFlag("1");
		dataTaskExRecordImage.setCreateTime(DateUtils.getNowDate());
		dataTaskExRecordImageMapper.insertDataTaskExRecordImage(dataTaskExRecordImage);
		return AjaxResult.success();
	}

	/**
	 * 删除营销反馈的图片
	 * 
	 * @param dataTaskExRecordImage
	 * @param userInfo
	 * @return
	 */
	public AjaxResult delExImage(DataTaskExRecordImage dataTaskExRecordImage, LoginUser userInfo) {
		if (StringUtils.isEmpty(dataTaskExRecordImage.getExId())) {
			return AjaxResult.error("营销反馈ID为空 >>exId");
		}
		if (StringUtils.isEmpty(dataTaskExRecordImage.getExPic())) {
			return AjaxResult.error("图片路径不能为空 >>exPic");
		}
		String exPic = dataTaskExRecordImage.getExPic();
		exPic = exPic.substring(exPic.indexOf("/test/files") + "/test/files".length());
		if (userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office")) {
			dataTaskExRecordImage.setTaskExRecordId(dataTaskExRecordImage.getExId());
			dataTaskExRecordImage.setUpdateTime(DateUtils.getNowDate());
			dataTaskExRecordImage.setCreateTime(null);
			dataTaskExRecordImage.setDelFlag("0");
			dataTaskExRecordImage.setExPic(exPic);
			dataTaskExRecordImageMapper.updateDataTaskExRecordImage(dataTaskExRecordImage);
			return AjaxResult.success();
		} else {
			// 其他的暂时不返回数据
			return AjaxResult.error("没有权限执行此操作");
		}
	}

	public AjaxResult delTaskInfo(DataTaskInfo taskInfo, LoginUser userInfo) {
		if (StringUtils.isEmpty(taskInfo.getTaskId())) {
			return AjaxResult.error("营销任务客户ID不能为空 >>taskId");
		}
		if (StringUtils.isEmpty(taskInfo.getIdCard())) {
			return AjaxResult.error("身份证号不能为空 >>idCard");
		}
		String taskId = taskInfo.getTaskId();
		String idCard = taskInfo.getIdCard();
		String complete = taskInfo.getComplete();

		if (userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office")) {
			if ("1".equals(complete)) {
				return AjaxResult.error();
			}
			int taskNum = dataTaskInfoMapper.getUserTaskNum(taskId);
			if (taskNum == 1) {
				dataTaskInfoMapper.deleteDataTaskInfoById(taskId);
			}

			dataTaskInfoMapper.deleteTaskRelation(taskId, idCard);
			dataTaskInfoMapper.deleteExRecord(taskId, idCard);
			return AjaxResult.success();
		} else {
			// 其他的暂时不返回数据
			return AjaxResult.error();
		}
	}

	public List<UserTaskRelationDO>  queryAllotTaskCustomer(UserTaskRelationDO userTaskRelationDO,LoginUser userInfo) {

		String orgId = userInfo.getSysUser().getDept().getOrgId();
        List<UserTaskRelationDO> doList = new ArrayList<UserTaskRelationDO>();
		//网格客户分配，只需要更新DATA_USER_TASK_RELATION 营销任务中的营销人即可
		UserTaskRelationDO vo = userTaskRelationDO;
	    if (null == vo)
	    {
	    	vo = new UserTaskRelationDO();
	    }
	    // 如果当前登陆的不是总行机构，则只查询本支行的
		if (userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office")) {
	    	
        }else {
        	vo.setOrgId(orgId);
        }
	    //0 全部客户  1已分配  2 待分配
		doList = dataUserTaskRelationMapper.allotTaskCustomer(vo);
//	    if("0".equals(vo.getFpType())) {
//			doList = dataUserTaskRelationMapper.allotTaskCustomer(vo);
//	    }else if("1".equals(vo.getFpType())){
//			doList = dataUserTaskRelationMapper.allotTaskCustomerYfp(vo);
//	    }else if("2".equals(vo.getFpType())){
//			doList = dataUserTaskRelationMapper.allotTaskCustomerDfp(vo);
//		}
	    
        return doList;
	}
	
	public AjaxResult AllotTaskCustomer(UserTaskRelationDO vo,LoginUser userInfo) {
		String orgId = userInfo.getSysUser().getDept().getOrgId();

		if (!(userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office"))) {
			if(!orgId.equals(vo.getOrgId())) {
				throw new CustomException("本支行客户只能转到本支行客户经理名下!");
			}
		}


		//表示为批量分配
		if(vo.getList()!=null&&vo.getList().size() > 0 ) {
			for(UserTaskRelationDO po: vo.getList()) {
				DataUserTaskRelation dataUserTaskRelation = new DataUserTaskRelation();
				dataUserTaskRelation.setOrgId(vo.getOrgId());
				dataUserTaskRelation.setUserId(vo.getUserId());
				DataUserTaskRelation dataUserTaskRelations = dataUserTaskRelationMapper.selectDataUserTaskRelationById(po.getId());
//				dataUserTaskRelation.setId(po.getId());
				dataUserTaskRelation.setIdCard(dataUserTaskRelations.getIdCard());
				dataUserTaskRelation.setTaskId(dataUserTaskRelations.getTaskId());
				dataUserTaskRelationMapper.updateDataUserTaskRelationByIdcard(dataUserTaskRelation);
			}
		}
		return AjaxResult.success();
	}
	
	
	
	/**
	 * 客户经理查看营销任务报表
	 * 
	 * @param condition
	 * @return
	 */
	public List<TaskReportsVO> getReportsByUser(DataTaskInfo condition) {
		List<DataTaskInfo> taskList = this.queryListByUser(condition.getOrgId(), condition.getUserId());

		if (ListUtil.isNullOrEmpty(taskList)) {
			return new ArrayList<TaskReportsVO>();
		}

		List<TaskReportsVO> taskReportsVOList = new ArrayList<>();

		for (DataTaskInfo temp : taskList) {
			UserTaskRelationDO userTaskRelationDO = new UserTaskRelationDO();
			userTaskRelationDO.setTaskId(temp.getTaskId());
			userTaskRelationDO.setOrgId(condition.getOrgId());
			userTaskRelationDO.setUserId(condition.getUserId());
			userTaskRelationDO.setComplete(Constant.TASK_COMPLETE_DONE);
			int done = dataUserTaskRelationMapper.reportsGroupByUser(userTaskRelationDO);
			userTaskRelationDO.setComplete(Constant.TASK_COMPLETE_UNDO);
			int todo = dataUserTaskRelationMapper.reportsGroupByUser(userTaskRelationDO);

			int total = done + todo;
			String jindu = IntegerUtil.int2String(done, total);
			TaskReportsVO reportsVO = new TaskReportsVO(temp.getTaskName(), todo, done, jindu);

			// 将百分比值转换为整数，用于排序
			reportsVO.setSort(IntegerUtil.String2Int(jindu));
			taskReportsVOList.add(reportsVO);
		}
		Collections.sort(taskReportsVOList);
		return taskReportsVOList;
	}

	/**
	 * 查询客户经理当前进行中的所有任务
	 * 
	 * @param orgId
	 * @param userId
	 * @return
	 */
	public List<DataTaskInfo> queryListByUser(String orgId, String userId) {
		DataTaskInfo condition = new DataTaskInfo();
		condition.setOrgId(orgId);
		condition.setUserId(userId);
		List<DataTaskInfo> taskInfoDOList = dataTaskInfoMapper.listByUser(condition);
		return taskInfoDOList;
	}

	/**
	 * 校验营销任务是否已开始，开始则返回true
	 *
	 * @param taskId
	 * @return
	 */
	private boolean checkTaskIfBegin(String taskId) {
		int count = dataTaskInfoMapper.checkTaskIfBegin(taskId);
		return 1 == count;
	}

	/**
	 * 校验营销任务是否已结束，结束则返回true
	 *
	 * @param taskId
	 * @return
	 */
	private boolean checkTaskIfEnd(String taskId) {
		int count = dataTaskInfoMapper.checkTaskIfEnd(taskId);
		return 1 == count;
	}

	/**
	 * 查询营销任务
	 * 
	 * @param taskId 营销任务ID
	 * @return 营销任务
	 */
	@Override
	public DataTaskInfo selectDataTaskInfoById(String taskId) {
		return dataTaskInfoMapper.selectDataTaskInfoById(taskId);
	}

	/**
	 * 查询营销任务列表
	 * 
	 * @param dataTaskInfo 营销任务
	 * @return 营销任务
	 */
	@Override
	public List<DataTaskInfo> selectDataTaskInfoList(DataTaskInfo dataTaskInfo) {
		return dataTaskInfoMapper.selectDataTaskInfoList(dataTaskInfo);
	}

	/**
	 * 新增营销任务
	 * 
	 * @param dataTaskInfo 营销任务
	 * @return 结果
	 */
	@Override
	public int insertDataTaskInfo(DataTaskInfo dataTaskInfo) {
		dataTaskInfo.setCreateTime(DateUtils.getNowDate());
		return dataTaskInfoMapper.insertDataTaskInfo(dataTaskInfo);
	}

	/**
	 * 修改营销任务
	 * 
	 * @param dataTaskInfo 营销任务
	 * @return 结果
	 */
	@Override
	public int updateDataTaskInfo(DataTaskInfo dataTaskInfo) {
		dataTaskInfo.setUpdateTime(DateUtils.getNowDate());
		return dataTaskInfoMapper.updateDataTaskInfo(dataTaskInfo);
	}

	/**
	 * 批量删除营销任务
	 * 
	 * @param taskIds 需要删除的营销任务ID
	 * @return 结果
	 */
	@Override
	public int deleteDataTaskInfoByIds(String[] taskIds) {
		return dataTaskInfoMapper.deleteDataTaskInfoByIds(taskIds);
	}

	/**
	 * 删除营销任务信息
	 * 
	 * @param taskId 营销任务ID
	 * @return 结果
	 */
	@Override
	public int deleteDataTaskInfoById(String taskId) {
		return dataTaskInfoMapper.deleteDataTaskInfoById(taskId);
	}

	public List<NewtableAll> getNewtableAllList(NewtableAll newtableAll, LoginUser userInfo){

		List<NewtableAll> newtableAllList = new ArrayList<NewtableAll>();

//		String orgId = userInfo.getSysUser().getDept().getOrgId();
//		String userId = userInfo.getSysUser().getUserName();
//
//		if (userInfo.getRoles().contains("admin") || userInfo.getRoles().contains("office")) {
//
//		} else if (userInfo.getRoles().contains("zhhz")) {
//			newtableAll.setOrgId(orgId);
//		} else if (userInfo.getRoles().contains("common")) {
//			newtableAll.setOrgId(orgId);
//			newtableAll.setUserId(userId);
//		}
		//获取没有下发过任务的客户
		newtableAll.setFlag("0");
		newtableAllList = dataTaskInfoMapper.selectNewtableAllList(newtableAll);
		return newtableAllList;
	}

}
